#include <stdio.h>
#include "tp_sound.h"

tp_sound_recording* recorded_sounds[RECORDED_SOUNDS_SIZE];
int free_recorded_sound_index;

// This function is used to initialize tp_sound values.
void tp_sound_initialize(void){
	int i;	
	for(i = 0; i < RECORDED_SOUNDS_SIZE; i++){
		recorded_sounds[i] = 0;	
	}
	free_recorded_sound_index = 0;

}

/* initializes tux paint sound */
void tp_sound_terminate(void){
	int i;
	for(i = 0; i < RECORDED_SOUNDS_SIZE; i++){
		free(recorded_sounds[i]);	
	}
}

/* get_recording returns the sound stored in the position 'n', if it doesn't exist then it returns null */ 
tp_sound_recording* tp_sound_get_recording(int n){ return recorded_sounds[n]; }

/* put_recording is used to store a sound in the recorded_sounds array */
int tp_sound_put_recording(tp_sound_recording* in_recording){
	if(tp_sound_recorded_sounds_full()){
	// if there aren't free slots return 0
		return 0;
	}else{
	// if there is a free slots
		// create a new recording
		tp_sound_recording* out_recording;
		out_recording = malloc(sizeof(tp_sound_recording));
		// resize the samples variable
		out_recording->size = in_recording->size;

		out_recording->samples = malloc(out_recording->size * sizeof(SAMPLE));
		// copy the data
		int i;
		for(i = 0; i < out_recording->size; i++){
			out_recording->samples[i] = in_recording->samples[i];		
		}
		out_recording->x = in_recording->x;
		out_recording->y = in_recording->y;
		out_recording->finished = in_recording->finished;
		// store in the next free slot
		recorded_sounds[free_recorded_sound_index] = out_recording;
		// increase free slot pointer
		free_recorded_sound_index++;
		return 1;
	}
}

/* recorded_sounds_full is used to see if the recorded_sounds array has indexes available or not */
int tp_sound_recorded_sounds_full(void){ return (free_recorded_sound_index == RECORDED_SOUNDS_SIZE); };

/* recorded_next_slot is used to retrieve the next free slot */
int tp_sound_next_slot(void){
	return free_recorded_sound_index;
}

/* recording_in_coordinates returns the recording in the square of side 2*offset and center x,y. If there is no recording, it returns a null pointer. 
  for example tp_sound_coordinates_recorded(10,20,5) will return a recording if there is one with x between 5 and 16 and y between 15 and 25 pixels.
*/
tp_sound_recording* tp_sound_recording_in_coordinates(int x, int y, int offset){
	int i;
	for(i = 0; i < free_recorded_sound_index; i++){
		if( (recorded_sounds[i]->x > x-offset) && (recorded_sounds[i]->x < x+offset) && (recorded_sounds[i]->y > y-offset) && (recorded_sounds[i]->y < y+offset)){
			return recorded_sounds[i];
		}
	}
	return 0;
}

